package cn.doit.dat06

import org.apache.commons.lang3.RandomUtils

import scala.util.Random

object _04_闭包 {
  def main(args: Array[String]): Unit = {

   /* val fun = (a:Int,b:Int)=>{
      val abc = 10
      a+b+abc
    }
    println(fun(1, 2))*///abc = 10 会被垃圾回收释放掉


   /* val fx = (a:Int,b:Int)=>{
      a+b
    }

    println(fx(1, 2))//3

    val fxx = (a:Int) => {
      (b:Int)=>a+b
    }

    val intToInt: Int => Int = fxx(1)
    println(intToInt(2))//3

    fxx(1)(2)//3
    val res = fxx(3)(10)*/
    val f = () => {
      //这个环境被称之为闭包
      var p = RandomUtils.nextInt(1,10)

      val inner = () => {
        p += 1
        p
      }
      inner
    }

    val x1= f()
    println(x1())//10
    println(x1())//11

    println("-----------")

    val x2 = f()
    println(x2())//4
    println(x2())//5
    println(x2())//6


    //调用f
/*    val newFun: () => Int = f() //这个函数执行完了，p= 10 也应该被回收
    //但是后面newFun中函数体里面也引用了这个随机数p
    println(newFun()) //这个p好像并没有被回收*/





  }

}
